<template>
  <view class="role-management-container">
    <!-- 顶部操作栏 -->
    <view class="action-bar">
      <view class="search-box">
        <input 
          class="search-input" 
          v-model="searchKeyword" 
          placeholder="搜索角色名称或描述"
          @input="handleSearch"
        />
        <text class="search-icon">🔍</text>
      </view>
      <button class="add-btn" @click="showAddDialog">+ 新增角色</button>
    </view>

    <!-- 角色列表 -->
    <view class="role-list">
      <view 
        class="role-item" 
        v-for="role in paginatedRoles" 
        :key="role.id"
        :class="{ disabled: role.status === '0' }"
      >
        <view class="role-info">
          <view class="role-name">{{ role.name }}</view>
          <view class="role-desc">{{ role.description }}</view>
          <view class="role-meta">
            <text>ID: {{ role.id }}</text>
            <text class="status" :class="{ active: role.status === '1' }">
              {{ role.status === '1' ? '已启用' : '已禁用' }}
            </text>
          </view>
        </view>
        <view class="role-actions">
          <switch 
            class="status-switch" 
            :checked="role.status === '1'" 
            @change="handleStatusChange(role)" 
            color="#4cd964"
          />
          <button class="action-btn edit" @click="handleEdit(role)">编辑</button>
          <button class="action-btn delete" @click="handleDelete(role.id)">删除</button>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-if="filteredRoles.length === 0">
      <image src="/static/empty.png" mode="aspectFit" />
      <text>暂无角色数据</text>
    </view>

    <!-- 分页控件 -->
    <view class="pagination" v-if="filteredRoles.length > 0">
      <button 
        class="page-btn" 
        :disabled="currentPage === 1" 
        @click="currentPage--"
      >
        上一页
      </button>
      <text class="page-info">第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</text>
      <button 
        class="page-btn" 
        :disabled="currentPage === totalPages" 
        @click="currentPage++"
      >
        下一页
      </button>
    </view>

    <!-- 添加/编辑弹窗 -->
    <view class="modal-mask" v-if="showDialog" @click="showDialog = false">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text>{{ dialogTitle }}</text>
          <text class="close-btn" @click="showDialog = false">×</text>
        </view>
        <view class="modal-body">
          <view class="form-item">
            <text class="form-label">角色名称</text>
            <input 
              class="form-input" 
              v-model="formData.name" 
              placeholder="请输入角色名称"
            />
          </view>
          <view class="form-item">
            <text class="form-label">角色描述</text>
            <textarea 
              class="form-textarea" 
              v-model="formData.description" 
              placeholder="请输入角色描述"
            />
          </view>
          <view class="form-item">
            <text class="form-label">状态</text>
            <radio-group class="radio-group" @change="handleStatusRadioChange">
              <label class="radio-item" v-for="item in statusOptions" :key="item.value">
                <radio :value="item.value" :checked="formData.status === item.value" />
                <text>{{ item.label }}</text>
              </label>
            </radio-group>
          </view>
          <view class="form-item">
            <text class="form-label">权限分配</text>
            <view class="permission-list">
              <view 
                class="permission-item" 
                v-for="permission in allPermissions" 
                :key="permission.id"
                @click="togglePermission(permission.id)"
              >
                <view class="permission-checkbox" :class="{ checked: formData.permissions.includes(permission.id) }">
                  {{ formData.permissions.includes(permission.id) ? '✓' : '' }}
                </view>
                <text class="permission-name">{{ permission.name }}</text>
              </view>
            </view>
          </view>
        </view>
        <view class="modal-footer">
          <button class="modal-btn cancel" @click="showDialog = false">取消</button>
          <button class="modal-btn confirm" @click="handleDialogConfirm">确认</button>
        </view>
      </view>
    </view>

    <!-- 删除确认弹窗 -->
    <view class="confirm-mask" v-if="showConfirmDialog">
      <view class="confirm-box">
        <text class="confirm-title">确认删除</text>
        <text class="confirm-content">确定要删除该角色吗？此操作不可撤销！</text>
        <view class="confirm-btns">
          <button class="confirm-btn cancel" @click="showConfirmDialog = false">取消</button>
          <button class="confirm-btn delete" @click="confirmDelete">删除</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
// 生成模拟数据
const generateMockData = () => {
  const roles = [];
  const roleNames = ['管理员', '编辑', '运营', '财务', '客服', '开发', '测试', '产品'];
  const descriptions = [
    '拥有系统所有权限',
    '负责内容编辑和发布',
    '负责运营活动管理',
    '负责财务数据管理',
    '负责客户服务工作',
    '负责系统开发和维护',
    '负责系统测试工作',
    '负责产品规划和设计'
  ];
  
  for (let i = 1; i <= 25; i++) {
    const randomIndex = Math.floor(Math.random() * roleNames.length);
    roles.push({
      id: i,
      name: `${roleNames[randomIndex]}${i > roleNames.length ? i : ''}`,
      description: descriptions[randomIndex],
      status: Math.random() > 0.3 ? '1' : '0',
      permissions: []
    });
  }
  return roles;
};

const generatePermissions = () => {
  return [
    { id: 'user:read', name: '查看用户' },
    { id: 'user:edit', name: '编辑用户' },
    { id: 'user:delete', name: '删除用户' },
    { id: 'content:read', name: '查看内容' },
    { id: 'content:edit', name: '编辑内容' },
    { id: 'content:publish', name: '发布内容' },
    { id: 'order:manage', name: '订单管理' },
    { id: 'data:analyze', name: '数据分析' },
    { id: 'system:config', name: '系统配置' },
    { id: 'log:view', name: '查看日志' }
  ];
};

export default {
  data() {
    return {
      // 角色数据
      allRoles: [],
      filteredRoles: [],
      paginatedRoles: [],
      // 分页
      currentPage: 1,
      pageSize: 8,
      // 搜索
      searchKeyword: '',
      // 弹窗控制
      showDialog: false,
      showConfirmDialog: false,
      dialogTitle: '添加角色',
      isEditMode: false,
      deletingId: null,
      // 表单数据
      formData: {
        id: null,
        name: '',
        description: '',
        status: '1',
        permissions: []
      },
      // 状态选项
      statusOptions: [
        { label: '启用', value: '1' },
        { label: '禁用', value: '0' }
      ],
      // 权限列表
      allPermissions: generatePermissions()
    };
  },
  computed: {
    totalPages() {
      return Math.ceil(this.filteredRoles.length / this.pageSize);
    }
  },
  created() {
    this.initData();
  },
  watch: {
    currentPage() {
      this.paginateData();
    },
    filteredRoles() {
      this.currentPage = 1;
      this.paginateData();
    }
  },
  methods: {
    // 初始化数据
    initData() {
      this.allRoles = generateMockData();
      this.filterRoles();
    },
    
    // 过滤角色
    filterRoles() {
      if (!this.searchKeyword) {
        this.filteredRoles = [...this.allRoles];
      } else {
        const keyword = this.searchKeyword.toLowerCase();
        this.filteredRoles = this.allRoles.filter(role => 
          role.name.toLowerCase().includes(keyword) || 
          role.description.toLowerCase().includes(keyword)
        );
      }
      this.paginateData();
    },
    
    // 分页处理
    paginateData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.paginatedRoles = this.filteredRoles.slice(start, end);
    },
    
    // 搜索处理
    handleSearch() {
      this.filterRoles();
    },
    
    // 显示添加弹窗
    showAddDialog() {
      this.dialogTitle = '添加角色';
      this.isEditMode = false;
      this.resetForm();
      this.showDialog = true;
    },
    
    // 编辑角色
    handleEdit(role) {
      this.dialogTitle = '编辑角色';
      this.isEditMode = true;
      this.formData = {
        id: role.id,
        name: role.name,
        description: role.description,
        status: role.status,
        permissions: [...role.permissions]
      };
      this.showDialog = true;
    },
    
    // 重置表单
    resetForm() {
      this.formData = {
        id: null,
        name: '',
        description: '',
        status: '1',
        permissions: []
      };
    },
    
    // 状态单选变化
    handleStatusRadioChange(e) {
      this.formData.status = e.detail.value;
    },
    
    // 切换权限选择
    togglePermission(permissionId) {
      const index = this.formData.permissions.indexOf(permissionId);
      if (index === -1) {
        this.formData.permissions.push(permissionId);
      } else {
        this.formData.permissions.splice(index, 1);
      }
    },
    
    // 弹窗确认
    handleDialogConfirm() {
      if (!this.formData.name.trim()) {
        uni.showToast({
          title: '请输入角色名称',
          icon: 'none'
        });
        return;
      }
      
      if (this.isEditMode) {
        // 更新角色
        const index = this.allRoles.findIndex(r => r.id === this.formData.id);
        if (index !== -1) {
          this.allRoles[index] = { ...this.formData };
          uni.showToast({
            title: '角色更新成功',
            icon: 'success'
          });
        }
      } else {
        // 添加角色
        const newId = Math.max(...this.allRoles.map(r => r.id)) + 1;
        this.allRoles.unshift({
          ...this.formData,
          id: newId
        });
        uni.showToast({
          title: '角色添加成功',
          icon: 'success'
        });
      }
      
      this.showDialog = false;
      this.filterRoles();
    },
    
    // 状态切换
    handleStatusChange(role) {
      role.status = role.status === '1' ? '0' : '1';
      const index = this.allRoles.findIndex(r => r.id === role.id);
      if (index !== -1) {
        this.allRoles[index].status = role.status;
      }
      uni.showToast({
        title: role.status === '1' ? '已启用角色' : '已禁用角色',
        icon: 'success'
      });
    },
    
    // 删除角色
    handleDelete(id) {
      this.deletingId = id;
      this.showConfirmDialog = true;
    },
    
    // 确认删除
    confirmDelete() {
      const index = this.allRoles.findIndex(r => r.id === this.deletingId);
      if (index !== -1) {
        this.allRoles.splice(index, 1);
        uni.showToast({
          title: '角色删除成功',
          icon: 'success'
        });
        this.filterRoles();
      }
      this.showConfirmDialog = false;
    }
  }
};
</script>

<style lang="scss">
/* 主容器 */
.role-management-container {
  padding: 20rpx;
  min-height: 100vh;
  background-color: #f5f7fa;
}

/* 操作栏 */
.action-bar {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
  gap: 20rpx;
}

.search-box {
  flex: 1;
  position: relative;
  background: #fff;
  border-radius: 50rpx;
  padding: 0 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.search-input {
  height: 80rpx;
  padding-left: 40rpx;
  font-size: 28rpx;
}

.search-icon {
  position: absolute;
  left: 30rpx;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
}

.add-btn {
  background: #2979ff;
  color: white;
  border: none;
  border-radius: 50rpx;
  padding: 0 40rpx;
  height: 80rpx;
  font-size: 28rpx;
  box-shadow: 0 4rpx 12rpx rgba(41, 121, 255, 0.3);
}

/* 角色列表 */
.role-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.role-item {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  
  &.disabled {
    opacity: 0.7;
  }
  
  &:active {
    transform: scale(0.98);
  }
}

.role-info {
  flex: 1;
}

.role-name {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
  color: #333;
}

.role-desc {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 15rpx;
}

.role-meta {
  display: flex;
  gap: 20rpx;
  font-size: 24rpx;
  color: #999;
}

.status {
  &.active {
    color: #4cd964;
  }
}

.role-actions {
  display: flex;
  align-items: center;
  gap: 15rpx;
}

.status-switch {
  transform: scale(0.8);
}

.action-btn {
  padding: 0 20rpx;
  height: 50rpx;
  line-height: 50rpx;
  font-size: 24rpx;
  border-radius: 25rpx;
  border: none;
  
  &.edit {
    background: #f0f7ff;
    color: #2979ff;
  }
  
  &.delete {
    background: #fff0f0;
    color: #ff4d4f;
  }
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  
  image {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 30rpx;
    opacity: 0.5;
  }
  
  text {
    color: #999;
    font-size: 28rpx;
  }
}

/* 分页 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 40rpx;
  gap: 30rpx;
}

.page-btn {
  background: #fff;
  border: 1rpx solid #eee;
  border-radius: 8rpx;
  padding: 0 30rpx;
  height: 60rpx;
  font-size: 26rpx;
  
  &:disabled {
    opacity: 0.5;
  }
}

.page-info {
  font-size: 26rpx;
  color: #666;
}

/* 弹窗 */
.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  width: 90%;
  max-width: 690rpx;
  background: white;
  border-radius: 20rpx;
  overflow: hidden;
  animation: modal-show 0.3s;
}

@keyframes modal-show {
  from { transform: scale(0.9); opacity: 0; }
  to { transform: scale(1); opacity: 1; }
}

.modal-header {
  padding: 30rpx;
  font-size: 32rpx;
  font-weight: bold;
  border-bottom: 1rpx solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.close-btn {
  font-size: 40rpx;
  color: #999;
}

.modal-body {
  padding: 30rpx;
  max-height: 70vh;
  overflow-y: auto;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  display: block;
  font-size: 28rpx;
  margin-bottom: 15rpx;
  color: #333;
}

.form-input, .form-textarea {
  width: 100%;
  padding: 20rpx;
  border: 1rpx solid #eee;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: #f9f9f9;
}

.form-textarea {
  height: 150rpx;
}

.radio-group {
  display: flex;
  gap: 40rpx;
}

.radio-item {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  
  radio {
    transform: scale(0.8);
    margin-right: 10rpx;
  }
}

.permission-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.permission-item {
  display: flex;
  align-items: center;
  padding: 15rpx;
  border-radius: 8rpx;
  background: #f9f9f9;
}

.permission-checkbox {
  width: 36rpx;
  height: 36rpx;
  border: 1rpx solid #ddd;
  border-radius: 6rpx;
  margin-right: 15rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24rpx;
  color: white;
  background: #f9f9f9;
  
  &.checked {
    background: #2979ff;
    border-color: #2979ff;
  }
}

.permission-name {
  font-size: 26rpx;
}

.modal-footer {
  display: flex;
  border-top: 1rpx solid #eee;
}

.modal-btn {
  flex: 1;
  height: 90rpx;
  line-height: 90rpx;
  font-size: 30rpx;
  border: none;
  border-radius: 0;
  
  &.cancel {
    background: white;
    color: #666;
    border-right: 1rpx solid #eee;
  }
  
  &.confirm {
    background: #2979ff;
    color: white;
  }
}

/* 确认弹窗 */
.confirm-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.confirm-box {
  width: 80%;
  max-width: 600rpx;
  background: white;
  border-radius: 20rpx;
  padding: 40rpx;
  text-align: center;
  animation: modal-show 0.3s;
}

.confirm-title {
  font-size: 32rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 20rpx;
}

.confirm-content {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 40rpx;
}

.confirm-btns {
  display: flex;
  gap: 20rpx;
}

.confirm-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 28rpx;
  border-radius: 40rpx;
  
  &.cancel {
    background: #f5f5f5;
    color: #666;
  }
  
  &.delete {
    background: #ff4d4f;
    color: white;
  }
}
</style>